<template>
  <div class="tenant-monitor">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <i class="el-icon-monitor"></i>
        租户监控
      </div>
      <div class="header-filters">
        <!-- 房间拓扑下拉框 -->
        <el-select 
          v-model="selectedTopology" 
          placeholder="房间拓扑"
          clearable
          class="topology-select"
          @change="handleTopologyChange"
          @focus="showTopologyDialog = true"
        >
          <el-option
            v-for="item in topologyOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        
        <!-- 仪表状态下拉框 -->
        <el-select 
          v-model="selectedMeterStatus" 
          placeholder="仪表状态"
          clearable
          class="status-select"
          @change="handleStatusChange"
        >
          <el-option
            v-for="item in meterStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        
        <!-- 搜索框 -->
        <el-input
          v-model="searchKeyword"
          placeholder="请输入搜索内容"
          clearable
          class="search-input"
          @input="handleSearch"
          @clear="handleSearch">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>
    </div>

    <!-- 拓扑树弹窗 -->
    <el-dialog
      title="房间拓扑"
      :visible.sync="showTopologyDialog"
      width="400px"
      class="topology-dialog"
    >
      <div class="topology-content">
        <div class="tree-search">
          <el-input 
            v-model="treeSearchText" 
            placeholder="请输入搜索内容" 
            size="small" 
            clearable
            @input="filterTree">
            <i slot="prefix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </div>
        <div class="tree-container">
          <el-tree
            :data="treeData"
            :props="treeProps"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            :expand-on-click-node="false"
            :default-expand-all="true"
            :highlight-current="true"
            @node-click="handleNodeClick"
            class="custom-tree">
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span class="tree-node-label">
                <i :class="getNodeIcon(data)" class="tree-node-icon"></i>
                {{ node.label }}
              </span>
            </span>
          </el-tree>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showTopologyDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmTopologySelection">确定</el-button>
      </div>
    </el-dialog>

    <!-- 区域监控卡片 -->
    <div class="monitor-container">
      <div 
        v-for="area in filteredMonitorData" 
        :key="area.name" 
        class="area-section"
      >
        <div class="area-header">
          <h3 class="area-title">
            <i class="el-icon-office-building"></i>
            {{ area.name }}
          </h3>
          <div class="area-stats">
            <span class="stat-item">
              <i class="el-icon-user"></i>
              {{ area.tenants.length }} 户
            </span>
            <span class="stat-item">
              <i class="el-icon-check"></i>
              在线: {{ getOnlineCount(area.tenants) }}
            </span>
            <span class="stat-item">
              <i class="el-icon-warning"></i>
              异常: {{ getAbnormalCount(area.tenants) }}
            </span>
          </div>
        </div>
        <div class="tenant-cards">
          <div 
            v-for="tenant in area.tenants" 
            :key="tenant.id"
            class="tenant-card"
            :class="getCardClass(tenant.status)"
          >
            <div class="card-header">
              <div class="tenant-info">
                <div class="tenant-avatar">
                  <i class="el-icon-user-solid"></i>
                </div>
                <div class="tenant-details">
                  <h4 class="tenant-name">{{ tenant.name }}</h4>
                  <div class="tenant-status">
                    <el-tag 
                      size="mini" 
                      :type="getStatusType(tenant.status)"
                    >
                      {{ tenant.statusText }}
                    </el-tag>
                  </div>
                </div>
              </div>
              <div class="balance-info">
                <div class="balance-amount">
                  <span class="currency">¥</span>
                  <span class="amount">{{ tenant.remainingAmount.toFixed(3) }}</span>
                </div>
                <div class="balance-label">剩余金额</div>
              </div>
            </div>
            <div class="card-content">
              <div class="usage-stats">
                <div class="stat-row">
                  <div class="stat-item">
                    <div class="stat-icon electric">
                      <i class="el-icon-lightning"></i>
                    </div>
                    <div class="stat-info">
                      <div class="stat-label">今日用电</div>
                      <div class="stat-value">{{ tenant.todayElectricity }}</div>
                    </div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-icon water">
                      <i class="el-icon-coffee-cup"></i>
                    </div>
                    <div class="stat-info">
                      <div class="stat-label">今日用水</div>
                      <div class="stat-value">{{ tenant.todayWater }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="card-actions">
              <el-button 
                type="primary" 
                size="mini" 
                icon="el-icon-view"
                @click="viewDetails(tenant)"
              >
                查看详情
              </el-button>
              <el-button 
                type="success" 
                size="mini" 
                icon="el-icon-money"
                @click="recharge(tenant)"
              >
                充值
              </el-button>
            </div>
          </div>
          <!-- 空状态 -->
          <div v-if="area.tenants.length === 0" class="empty-area">
            <i class="el-icon-house"></i>
            <p>该区域暂无租户</p>
          </div>
        </div>
      </div>
      
      <!-- 无数据状态 -->
      <div v-if="filteredMonitorData.length === 0" class="no-data">
        <i class="el-icon-search"></i>
        <p>未找到符合条件的数据</p>
        <el-button type="primary" @click="resetFilters">重置筛选</el-button>
      </div>
    </div>
    <!-- 详情弹窗 -->
    <el-dialog
      title="租户详情"
      :visible.sync="showDetailDialog"
      width="600px"
      class="custom-dialog"
    >
      <div v-if="selectedTenant" class="tenant-detail">
        <div class="detail-header">
          <div class="tenant-avatar large">
            <i class="el-icon-user-solid"></i>
          </div>
          <div class="tenant-info">
            <h3>{{ selectedTenant.name }}</h3>
            <el-tag :type="getStatusType(selectedTenant.status)">
              {{ selectedTenant.statusText }}
            </el-tag>
          </div>
        </div>
        <div class="detail-content">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-item">
                <label>剩余金额:</label>
                <span class="value">¥{{ selectedTenant.remainingAmount.toFixed(3) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>今日用电:</label>
                <span class="value">{{ selectedTenant.todayElectricity }} kWh</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>今日用水:</label>
                <span class="value">{{ selectedTenant.todayWater }} m³</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-item">
                <label>状态:</label>
                <span class="value">{{ selectedTenant.statusText }}</span>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="recharge(selectedTenant)">充值</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import tenantMonitorMock from '@/api/mock/tenantMonitor'

export default {
  name: 'TenantMonitor',
  data() {
    return {
      // 搜索和过滤
      searchKeyword: '',
      selectedTopology: '',
      selectedMeterStatus: '',
      
      // 拓扑树相关
      showTopologyDialog: false,
      treeSearchText: '',
      selectedNode: null,
      treeData: [],
      treeProps: {
        children: 'children',
        label: 'label'
      },
      
      // 下拉选项
      topologyOptions: [
        { value: 'all', label: '全部区域' },
        { value: 'commercial', label: '微电网研究院_商业' },
        { value: 'floor1', label: 'A栋_1层' },
        { value: 'floor2', label: 'A栋_2层' },
        { value: 'floor3', label: 'A栋_3层' }
      ],
      meterStatusOptions: [
        { value: '', label: '全部状态' },
        { value: 'online', label: '离线' },
        { value: 'offline', label: '未开户' },
        { value: 'arrears', label: '欠费' },
        { value: 'normal', label: '报警' },
        { value: 'abnormal', label: '正常' },
        { value: 'warning', label: '异常' }
      ],
      
      // 数据
      monitorData: [],
      originalMonitorData: [],
      statusOptions: [],
      showDetailDialog: false,
      selectedTenant: null,
      
      // 防抖定时器
      searchTimer: null
    }
  },
  
  computed: {
    // 过滤后的监控数据
    filteredMonitorData() {
      let filtered = JSON.parse(JSON.stringify(this.originalMonitorData))
      
      // 根据拓扑过滤
      if (this.selectedTopology && this.selectedTopology !== 'all') {
        filtered = filtered.filter(area => {
          if (this.selectedTopology === 'commercial') {
            return area.name.includes('微电网研究院_商业')
          } else if (this.selectedTopology === 'floor1') {
            return area.name.includes('A栋_1层')
          } else if (this.selectedTopology === 'floor2') {
            return area.name.includes('A栋_2层')
          } else if (this.selectedTopology === 'floor3') {
            return area.name.includes('A栋_3层')
          }
          return true
        })
      }
      
      // 根据选中的树节点过滤
      if (this.selectedNode && this.selectedNode.id !== 'root') {
        filtered = filtered.filter(area => {
          if (this.selectedNode.type === 'building') {
            return area.name.includes(this.selectedNode.label)
          } else if (this.selectedNode.type === 'floor') {
            return area.name.includes(this.selectedNode.label)
          } else if (this.selectedNode.type === 'room') {
            return area.tenants.some(tenant => 
              tenant.roomNumber === this.selectedNode.label
            )
          }
          return true
        })
      }
      
      // 根据仪表状态过滤
      if (this.selectedMeterStatus) {
        filtered = filtered.map(area => ({
          ...area,
          tenants: area.tenants.filter(tenant => 
            tenant.status === this.selectedMeterStatus
          )
        })).filter(area => area.tenants.length > 0)
      }
      
      // 根据搜索关键词过滤
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        filtered = filtered.map(area => ({
          ...area,
          tenants: area.tenants.filter(tenant => 
            tenant.name.toLowerCase().includes(keyword) ||
            tenant.roomNumber.toLowerCase().includes(keyword) ||
            area.name.toLowerCase().includes(keyword)
          )
        })).filter(area => area.tenants.length > 0)
      }
      
      return filtered
    }
  },
  
  mounted() {
    this.loadData()
    this.loadTreeData()
  },
  
  methods: {
    // 加载数据
    loadData() {
      const response = tenantMonitorMock
      this.originalMonitorData = response.msg.areas
      this.monitorData = JSON.parse(JSON.stringify(this.originalMonitorData))
      this.statusOptions = response.msg.statusOptions
    },
    
    // 加载树形数据
    loadTreeData() {
      this.treeData = [
        {
          id: 'root',
          label: '微电网研究院',
          type: 'root',
          children: [
            {
              id: 'commercial',
              label: '商业',
              type: 'building',
              children: [
                {
                  id: 'floor1',
                  label: 'A栋_1层',
                  type: 'floor',
                  children: [
                    { id: 'room101', label: '101', type: 'room' },
                    { id: 'room102', label: '102', type: 'room' },
                    { id: 'room103', label: '103', type: 'room' }
                  ]
                },
                {
                  id: 'floor2',
                  label: 'A栋_2层',
                  type: 'floor',
                  children: [
                    { id: 'room201', label: '201', type: 'room' },
                    { id: 'room202', label: '202', type: 'room' }
                  ]
                },
                {
                  id: 'floor3',
                  label: 'A栋_3层',
                  type: 'floor',
                  children: [
                    { id: 'room301', label: '301', type: 'room' }
                  ]
                }
              ]
            }
          ]
        }
      ]
    },
    
    // 拓扑变化处理
    handleTopologyChange(value) {
      console.log('拓扑变化:', value)
      this.selectedNode = null // 清除树选择
      this.applyFilters()
    },
    
    // 状态变化处理
    handleStatusChange(value) {
      console.log('状态变化:', value)
      this.applyFilters()
    },
    
    // 搜索处理（防抖）
    handleSearch() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }
      this.searchTimer = setTimeout(() => {
        console.log('搜索:', this.searchKeyword)
        this.applyFilters()
      }, 300)
    },
    
    // 应用过滤器
    applyFilters() {
      // 过滤逻辑在computed中处理
      this.$nextTick(() => {
        console.log('过滤结果:', this.filteredMonitorData.length, '个区域')
      })
    },
    
    // 树形过滤
    filterTree() {
      this.$refs.tree.filter(this.treeSearchText)
    },
    
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    
    // 树节点点击
    handleNodeClick(data) {
      console.log('选中节点:', data)
      this.selectedNode = data
      // 如果选择了具体节点，清除拓扑下拉选择
      if (data.id !== 'root') {
        this.selectedTopology = ''
      }
    },
    
    // 确认拓扑选择
    confirmTopologySelection() {
      if (this.selectedNode) {
        console.log('确认选择节点:', this.selectedNode.label)
        this.$message.success(`已选择: ${this.selectedNode.label}`)
      }
      this.showTopologyDialog = false
    },
    
    // 获取节点图标
    getNodeIcon(data) {
      const iconMap = {
        'root': 'el-icon-office-building',
        'building': 'el-icon-house',
        'floor': 'el-icon-menu',
        'room': 'el-icon-door'
      }
      return iconMap[data.type] || 'el-icon-folder'
    },
    
    // 重置过滤器
    resetFilters() {
      this.searchKeyword = ''
      this.selectedTopology = ''
      this.selectedMeterStatus = ''
      this.selectedNode = null
      this.treeSearchText = ''
      this.$message.success('已重置所有筛选条件')
    },
    
    // 统计方法
    getOnlineCount(tenants) {
      return tenants.filter(t => t.status === 'online').length
    },
    
    getAbnormalCount(tenants) {
      return tenants.filter(t => t.status === 'arrears' || t.status === 'offline').length
    },
    
    // 原有方法
    getCardClass(status) {
      return {
        'card-online': status === 'online',
        'card-arrears': status === 'arrears',
        'card-offline': status === 'offline'
      }
    },
    
    getStatusType(status) {
      const statusMap = {
        'online': 'success',
        'arrears': 'danger',
        'offline': 'info',
        'normal': 'success',
        'abnormal': 'warning'
      }
      return statusMap[status] || 'info'
    },
    
    viewDetails(tenant) {
      this.selectedTenant = tenant
      this.showDetailDialog = true
    },
    
    recharge(tenant) {
      this.$message.success(`为 ${tenant.name} 发起充值`)
    }
  }
}
</script>
<style scoped>
/* 主容器样式 */
.tenant-monitor {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.page-title {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}

.page-title i {
  color: #3498db;
  font-size: 28px;
}

.header-filters {
  display: flex;
  gap: 16px;
  align-items: center;
}

.topology-select,
.status-select {
  width: 150px;
}

.search-input {
  width: 250px;
}

/* 拓扑树弹窗样式 */
.topology-dialog .el-dialog__body {
  padding: 20px;
}

.topology-content {
  max-height: 400px;
}

.tree-search {
  margin-bottom: 16px;
}

.tree-container {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 12px;
}

.custom-tree {
  background: transparent;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  font-size: 14px;
  padding-right: 8px;
}

.tree-node-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tree-node-icon {
  color: #3498db;
  font-size: 16px;
}

/* 无数据状态 */
.no-data {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.no-data i {
  font-size: 64px;
  color: #dee2e6;
  margin-bottom: 16px;
}

.no-data p {
  color: #6c757d;
  font-size: 16px;
  margin-bottom: 20px;
}
/* 面包屑导航 */
.breadcrumb-nav {
  margin-bottom: 24px;
}
.breadcrumb-nav .el-breadcrumb {
  font-size: 14px;
}
.breadcrumb-nav .el-breadcrumb__item {
  color: #6c757d;
}
/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}
.page-title {
  margin: 0;
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 12px;
}
.page-title i {
  color: #3498db;
  font-size: 28px;
}
.header-filters {
  display: flex;
  gap: 16px;
  align-items: center;
}
.search-input {
  width: 300px;
}
.status-select {
  width: 150px;
}
/* 监控容器 */
.monitor-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}
/* 区域部分 */
.area-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
.area-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}
.area-title {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}
.area-title i {
  color: #3498db;
  font-size: 20px;
}
.area-stats {
  display: flex;
  gap: 16px;
}
.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6c757d;
  font-size: 14px;
}
.stat-item i {
  color: #3498db;
}
/* 租户卡片 */
.tenant-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
  padding: 24px;
}
.tenant-card {
  background: white;
  border-radius: 12px;
  border: 2px solid #e9ecef;
  padding: 20px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}
.tenant-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}
.tenant-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: #e9ecef;
  transition: all 0.3s ease;
}
.card-online::before {
  background: linear-gradient(90deg, #27ae60, #2ecc71);
}
.card-arrears::before {
  background: linear-gradient(90deg, #e74c3c, #c0392b);
}
.card-offline::before {
  background: linear-gradient(90deg, #95a5a6, #7f8c8d);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}
.tenant-info {
  display: flex;
  gap: 12px;
  align-items: center;
}
.tenant-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #3498db, #2980b9);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}
.tenant-avatar.large {
  width: 64px;
  height: 64px;
  font-size: 28px;
}
.tenant-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.tenant-name {
  margin: 0;
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}
.balance-info {
  text-align: right;
}
.balance-amount {
  display: flex;
  align-items: baseline;
  justify-content: flex-end;
  gap: 2px;
}
.currency {
  color: #6c757d;
  font-size: 14px;
}
.amount {
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
}
.balance-label {
  color: #6c757d;
  font-size: 12px;
  margin-top: 4px;
}
.card-content {
  margin-bottom: 16px;
}
.usage-stats {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}
.stat-row {
  display: flex;
  gap: 20px;
}
.usage-stats .stat-item {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}
.stat-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}
.stat-icon.electric {
  background: linear-gradient(135deg, #f39c12, #e67e22);
}
.stat-icon.water {
  background: linear-gradient(135deg, #3498db, #2980b9);
}
.stat-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.stat-label {
  color: #6c757d;
  font-size: 12px;
}
.stat-value {
  color: #2c3e50;
  font-size: 16px;
  font-weight: 600;
}
.card-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}
.card-actions .el-button {
  border-radius: 6px;
  font-size: 12px;
  padding: 8px 16px;
}
/* 空状态 */
.empty-area {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px;
  color: #6c757d;
}
.empty-area i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #dee2e6;
}
.empty-area p {
  margin: 0;
  font-size: 16px;
}
/* 详情弹窗 */
.tenant-detail {
  padding: 20px 0;
}
.detail-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e9ecef;
}
.detail-header .tenant-info h3 {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 20px;
  font-weight: 600;
}
.detail-content .info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f8f9fa;
}
.detail-content .info-item label {
  color: #6c757d;
  font-weight: 500;
}
.detail-content .info-item .value {
  color: #2c3e50;
  font-weight: 600;
}
/* 响应式设计 */
@media (max-width: 768px) {
  .tenant-monitor {
    padding: 16px;
  }
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  .header-filters {
    width: 100%;
    justify-content: space-between;
  }
  .search-input {
    width: 200px;
  }
  .tenant-cards {
    grid-template-columns: 1fr;
    gap: 16px;
    padding: 16px;
  }
  .area-header {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
}
/* 动画效果 */
.tenant-card {
  animation: fadeInUp 0.3s ease;
}
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
